package net.starwifi.duobao.plugin.wo3;



import cn.com.hongpay.client.gen.ReqMsgGenerate;
import cn.com.hongpay.client.utils.CommonTools;
import cn.com.hongpay.client.vo.refund.RefundVo;
import net.starwifi.duobao.SettingUtils;
import net.starwifi.duobao.entity.*;
import net.starwifi.duobao.hfg.notify.NotifyInfo;
import net.starwifi.duobao.hfg.notify.NotifyResponse;
import net.starwifi.duobao.hfg.notify.NotifyTradeDetail;
import net.starwifi.duobao.hfg.payment.PayTradeDetail;
import net.starwifi.duobao.hfg.payment.PaymentRequest;
import net.starwifi.duobao.hfg.payment.TransSum;
import net.starwifi.duobao.hfg.query.QueryRequest;
import net.starwifi.duobao.hfg.query.QueryResponse;
import net.starwifi.duobao.hfg.refund.RefundRequest;
import net.starwifi.duobao.hfg.refund.RefundResponse;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.plugin.PaymentPlugin;
import net.starwifi.duobao.plugin.wo3.tool.PaymentNotifyRequest;
import net.starwifi.duobao.service.RefundsService;
import net.starwifi.duobao.utils.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Plugin - 话付购(即时交易)
 *
 * @author ruoo
 * @version 1.0
 */
@Component("wo3DirectPlugin")
public class Wo3DirectPlugin extends PaymentPlugin {


    @Autowired
    RefundsService refundsService;

    @Override
    public String getName() {
        return "话付购";
    }

    @Override
    public String getVersion() {
        return "1.0";
    }

    @Override
    public String getAuthor() {
        return "ruoo";
    }

    @Override
    public String getSiteUrl() {
        return "http://duobao.com";
    }

    @Override
    public String getInstallUrl() {
        return "wo3Direct/install";
    }

    @Override
    public String getUninstallUrl() {
        return "wo3Direct/uninstall";
    }

    @Override
    public String getSettingUrl() {
        return "wo3Direct/setting";
    }

    @Override
    public String getRequestUrl() {
        //return "https://www.hfgo.com.cn/aipay_web/web/woWebPay.do";
        //return "http://120.52.21.138:8090/aipay_web/web/woWebPay.do";
        return "https://www.hfgo.com.cn/aiPayServPortal/html/wappay/aipaySubmitOrderWap";
        //return "http://120.52.21.138:8091/aiPayServPortal/html/wappay/aipaySubmitOrderWap";
    }

    @Override
    public RequestMethod getRequestMethod() {
        return RequestMethod.post;
    }

    @Override
    public String getRequestCharset() {
        return "UTF-8";
    }


    /**
     * 创建支付报文
     */
    @Override
    public Map<String, Object> getParameterMap(Payment payment, String description, HttpServletRequest request) {
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        String pfxFile = null;
        String pfxPwd = null;
        String privateKeyPwd = null;
        String cerFile = null;
        String partnerId = null;
        String partnerVerifyCode = null;
        String acctId = null;
        String acctName = null;
        String host = null;
        String mobile = null;
        String keyPath = SettingUtils.get("keyPath");
        pfxFile = keyPath + "/starwifi_private.pfx"; // 合作方的私钥文件路径
        pfxPwd = "starwifi_7982!"; // 私钥库密码
        privateKeyPwd = "starwifi@1532%";// 私钥密码
        cerFile = keyPath + "/huaft_public.cer"; // 合作方的私钥文件路径
        partnerId = "100004";
        partnerVerifyCode = "343D35167272373596FBA8291C6AB3B8";
        acctId = "app_baoxb";
        acctName = "0元夺宝";
//        if (payment.getFlag().equals(DBProduct.FLAG_YX)) {
//            partnerId = "100012";
//            partnerVerifyCode = "2B989953E6B4F3F83A8F870796844272";
//            acctId = "app_baomall";
//            acctName = "0元夺流量";
//        }

        ReqMsgGenerate reqMsgGenerate = new ReqMsgGenerate(pfxFile, pfxPwd, privateKeyPwd);
        reqMsgGenerate.setCharset("UTF-8");

        /*********************************************************
         * 构造支付请求报文(以下程序仅供参考，使用请按照接口文档set相应的值）
         ******************************************************/
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String requestTime = df.format(new Date());
        if (request.getSession().getAttribute("pMobile") != null) {
            mobile = request.getSession().getAttribute("pMobile").toString();
        }
        //新支付接口 start
        String goods_name = StringUtils.abbreviate(description.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5 ]", ""), 60);
        String goods_type = "4";
        Long pay_amount = payment.getAmount().multiply(new BigDecimal(100)).longValue();
        //mobile="18550362376"; //测试号码
        PayTradeDetail tradeDetail = new PayTradeDetail("", goods_name, goods_type, payment.getOrderSn(), acctId, pay_amount);
        TransSum transSum = new TransSum("");
        PaymentRequest req = new PaymentRequest(mobile, partnerId, partnerVerifyCode, requestTime, tradeDetail, transSum);
        // 生成签名的支付请求报文
        String reqSignMsg = req.encode(pfxFile, pfxPwd, privateKeyPwd);
        System.out.println(reqSignMsg);
        parameterMap.put("requestPacket", reqSignMsg);
        return parameterMap;
    }


    /**
     * 支付通知校验
     */
    @SuppressWarnings("unchecked")
    @Override
    public boolean verifyNotify(Payment payment, NotifyMethod notifyMethod, String data, HttpServletRequest request) {
        PaymentNotifyRequest req = PaymentNotifyRequest.getNotify(data);
        if (req.getPartnerTradeNo() == null) {
            return false;
        }
        if (req.getResultCode().equals("00")) {
            return true;
        }
        return false;
    }

    /**
     * 支付结果通知
     */
//	@Override
//	public String getNotifyMessage(Payment payment, NotifyMethod notifyMethod,String data, HttpServletRequest request) {
//		PaymentNotifyRequest req=PaymentNotifyRequest.getNotify(data);
//		return req.getResponse("00",payment.getFlag());
//	}
    @Override
    public String getNotifyMessage(Payment payment, NotifyMethod notifyMethod, NotifyTradeDetail detail, HttpServletRequest request) {
        //调用该部时确认已经检查订单状态
        String pfxFile = null;
        String pfxPwd = null;
        String privateKeyPwd = null;
        String cerFile = null;
        String partnerId = null;
        String partnerVerifyCode = null;
        String acctId = null;
        String acctName = null;
        String host = null;
        String keyPath = SettingUtils.get("keyPath");
        pfxFile = keyPath + "/starwifi_private.pfx"; // 合作方的私钥文件路径
        pfxPwd = "starwifi_7982!"; // 私钥库密码
        privateKeyPwd = "starwifi@1532%";// 私钥密码
        cerFile = keyPath + "/huaft_public.cer"; // 合作方的私钥文件路径
        partnerId = "100004";
        partnerVerifyCode = "343D35167272373596FBA8291C6AB3B8";
        acctId = "app_baoxb";
        acctName = "0元夺宝";
//        if (payment.getFlag().equals(DBProduct.FLAG_YX)) {
//            partnerId = "100012";
//            partnerVerifyCode = "2B989953E6B4F3F83A8F870796844272";
//            acctId = "app_baomall";
//            acctName = "0元夺流量";
//        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String requestTime = df.format(new Date());
        NotifyInfo info = new NotifyInfo(partnerId, partnerVerifyCode, requestTime);

        NotifyResponse res = new NotifyResponse(info, detail);
        String json = res.encode(pfxFile, pfxPwd, privateKeyPwd);
        System.out.println("JSON##########" + json);
        return json;
    }


    @Override
    public Message refund(Refunds refunds, HttpServletRequest request) {
        return null;
    }

    /**
     * 退款
     */
    @Override
    public RefundResponse refunds(String sn, HttpServletRequest request) {
        //String url="http://120.52.21.138:8091/aiPayServPortal/rest/pay/aipayRefund";
        String url = "https://www.hfgo.com.cn/aiPayServPortal/rest/pay/aipayRefund";
        Refunds refunds = refundsService.findByOrderSn(sn);
        String str = createRefundString(refunds, request);
        String result = HttpUtils.postJson(url, str);
        System.out.println(result);
        //解析响应
        RefundResponse res = new RefundResponse();
        res.parseRes(result);
        return res;
    }

    @Override
    public QueryResponse query(Payment payment, HttpServletRequest request) {
        //String url="http://120.52.21.138:8091/aiPayServPortal/rest/pay/aipayQuery";
        String url = "https://www.hfgo.com.cn/aiPayServPortal/rest/pay/aipayQuery";
        String str = createQueryString(payment, request);
        System.out.println("查询请求:" + str);
        String result = HttpUtils.postJson(url, str);
        System.out.println("查询响应:" + result);
        //解析响应
        QueryResponse res = new QueryResponse();
        res.parseRes(result);
        return res;
    }

    /**
     * 创建退款字符串
     */
    private String createRefundRequest(Refunds refunds, HttpServletRequest request) {
        //调用该部时确认已经检查订单状态
        String pfxFile = null;
        String pfxPwd = null;
        String privateKeyPwd = null;
        String cerFile = null;
        String partnerId = null;
        String partnerVerifyCode = null;
        String acctId = null;
        String acctName = null;
        String host = null;
        String keyPath = SettingUtils.get("keyPath");
        pfxFile = keyPath + "/starwifi_private.pfx"; // 合作方的私钥文件路径
        pfxPwd = "starwifi_7982!"; // 私钥库密码
        privateKeyPwd = "starwifi@1532%";// 私钥密码
        cerFile = keyPath + "/huaft_public.cer"; // 合作方的私钥文件路径
        partnerId = "100004";
        partnerVerifyCode = "343D35167272373596FBA8291C6AB3B8";
        acctId = "app_baoxb";
        acctName = "0元夺宝";
        if (refunds.getFlag().equals(DBProduct.FLAG_YX)) {
            partnerId = "100012";
            partnerVerifyCode = "2B989953E6B4F3F83A8F870796844272";
            acctId = "app_baomall";
            acctName = "0元夺流量";
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ReqMsgGenerate reqMsgGenerate = new ReqMsgGenerate(pfxFile, pfxPwd, privateKeyPwd);
        reqMsgGenerate.setCharset("UTF-8");
        RefundVo vo = new RefundVo();
        vo.setServiceType("80");
        vo.setClientIp(CommonTools.getClientAddr(request));
        vo.setPartnerId(partnerId);
        vo.setPartnerVerifyCode(partnerVerifyCode);
        try {
            Date d = df.parse(df.format(new Date()));
            vo.setRequestTime(d); //需要格式化 YYYY-MM-DD HH24:MI:SS
            vo.setRefundTime(d); //需要格式化
        } catch (ParseException e) {
            e.printStackTrace();
        }
        vo.setPartnerTradeNo(refunds.getOrderSn());
        vo.setRefundAmount(refunds.getAmount().longValue() * 100);//金额
        String siteUrl = SettingUtils.get("siteUrl");
        vo.setRefundNotifyUrl(siteUrl + "/refund/notify/" + refunds.getSn());
        String reqSignMsg = "";
        try {
            reqSignMsg = reqMsgGenerate.generateRefundMsg(vo);
            reqSignMsg = reqSignMsg.replaceAll("\"", "\\\"");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reqSignMsg;
    }

    /**
     * 创建查询字符串
     */
    private String createQueryString(Payment payment, HttpServletRequest request) {
        //调用该部时确认已经检查订单状态
        String pfxFile = null;
        String pfxPwd = null;
        String privateKeyPwd = null;
        String cerFile = null;
        String partnerId = null;
        String partnerVerifyCode = null;
        String acctId = null;
        String acctName = null;
        String host = null;
        String keyPath = SettingUtils.get("keyPath");
        pfxFile = keyPath + "/starwifi_private.pfx"; // 合作方的私钥文件路径
        pfxPwd = "starwifi_7982!"; // 私钥库密码
        privateKeyPwd = "starwifi@1532%";// 私钥密码
        cerFile = keyPath + "/huaft_public.cer"; // 合作方的私钥文件路径
        partnerId = "100004";
        partnerVerifyCode = "343D35167272373596FBA8291C6AB3B8";
        acctId = "app_baoxb";
        acctName = "0元夺宝";
//        if (payment.getFlag().equals(DBProduct.FLAG_YX)) {
//            partnerId = "100012";
//            partnerVerifyCode = "2B989953E6B4F3F83A8F870796844272";
//            acctId = "app_baomall";
//            acctName = "0元夺流量";
//        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String requestTime = df.format(new Date());
        String refundTime = df.format(new Date());

        QueryRequest req = new QueryRequest(payment.getOrderSn(), "查询订单", requestTime, partnerId, partnerVerifyCode, "70");
        // 生成签名的支付请求报文
        String reqSignMsg = req.encode(pfxFile, pfxPwd, privateKeyPwd);
        return reqSignMsg;
    }


    /**
     * 创建退款字符串
     */
    private String createRefundString(Refunds refunds, HttpServletRequest request) {
        //调用该部时确认已经检查订单状态
        String pfxFile = null;
        String pfxPwd = null;
        String privateKeyPwd = null;
        String cerFile = null;
        String partnerId = null;
        String partnerVerifyCode = null;
        String acctId = null;
        String acctName = null;
        String host = null;
        String keyPath = SettingUtils.get("keyPath");
        pfxFile = keyPath + "/starwifi_private.pfx"; // 合作方的私钥文件路径
        pfxPwd = "starwifi_7982!"; // 私钥库密码
        privateKeyPwd = "starwifi@1532%";// 私钥密码
        cerFile = keyPath + "/huaft_public.cer"; // 合作方的私钥文件路径
        partnerId = "100004";
        partnerVerifyCode = "343D35167272373596FBA8291C6AB3B8";
        acctId = "app_baoxb";
        acctName = "0元夺宝";
        if (refunds.getFlag().equals(DBProduct.FLAG_YX)) {
            partnerId = "100012";
            partnerVerifyCode = "2B989953E6B4F3F83A8F870796844272";
            acctId = "app_baomall";
            acctName = "0元夺流量";
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String requestTime = df.format(new Date());
        String refundTime = df.format(new Date());

        Long refundAmount = refunds.getAmount().multiply(new BigDecimal(100)).longValue();
        RefundRequest req = new RefundRequest(refunds.getOrderSn(), refundAmount, refundTime, partnerId, partnerVerifyCode, requestTime);
        // 生成签名的支付请求报文
        String reqSignMsg = req.encode(pfxFile, pfxPwd, privateKeyPwd);
        return reqSignMsg;
    }


    @Override
    public Integer getTimeout() {
        return 21600;
    }

}